from flask import Flask, request, jsonify
from flasgger import Swagger, SwaggerUI, swag_from

app = Flask(__name__)
app.config['SWAGGER'] = {
    'title': '用户管理API',
    'uiversion': 3,
    'openapi': '3.0.2'
}
swagger = Swagger(app)



users = [
    {"id": 1, "name": "Alice", "email": "alice@example.com"},
    {"id": 2, "name": "Bob", "email": "bob@example.com"}
]


@app.route('/users', methods=['GET'])
@swag_from({
    'tags': ['用户管理'],
    'summary': '获取用户列表',
    'responses': {
        200: {
            'description': '用户列表',
            'content': {
                'application/json': {
                    'schema': {
                        'type': 'array',
                        'items': {'$ref': '#/components/schemas/User'}
                    }
                }
            }
        }
    }
})
def get_users():
    """获取所有用户信息"""
    return jsonify(users), 200


@app.route('/users/<int:user_id>', methods=['GET'])
@swag_from({
    'tags': ['用户管理'],
    'summary': '通过ID获取用户',
    'parameters': [{
        'name': 'user_id',
        'in': 'path',
        'required': True,
        'schema': {'type': 'integer'},
        'description': '用户唯一ID'
    }],
    'responses': {
        200: {
            'description': '用户详细信息',
            'content': {'application/json': {'schema': {'$ref': '#/components/schemas/User'}}}
        },
        404: {'description': '用户不存在'}
    }
})
def get_user(user_id):
    """根据ID查询单个用户"""
    user = next((u for u in users if u['id'] == user_id), None)
    return jsonify(user) if user else ('', 404)


@app.route('/users', methods=['POST'])
@swag_from({
    'tags': ['用户管理'],
    'summary': '创建新用户',
    'requestBody': {
        'required': True,
        'content': {
            'application/json': {
                'schema': {'$ref': '#/components/schemas/UserCreate'}
            }
        }
    },
    'responses': {
        201: {
            'description': '创建成功的用户',
            'content': {'application/json': {'schema': {'$ref': '#/components/schemas/User'}}}
        },
        400: {'description': '无效输入'}
    }
})
def create_user():
    """创建新用户"""
    data = request.get_json()
    if not data or 'name' not in data or 'email' not in data:
        return jsonify({"error": "缺少必要字段"}), 400

    new_user = {
        'id': len(users) + 1,
        'name': data['name'],
        'email': data['email']
    }
    users.append(new_user)
    return jsonify(new_user), 201


# Swagger组件定义
swagger.config['components'] = {
    'schemas': {
        'User': {
            'type': 'object',
            'properties': {
                'id': {'type': 'integer', 'format': 'int64'},
                'name': {'type': 'string'},
                'email': {'type': 'string', 'format': 'email'}
            }
        },
        'UserCreate': {
            'type': 'object',
            'required': ['name', 'email'],
            'properties': {
                'name': {'type': 'string', 'example': 'John Doe'},
                'email': {'type': 'string', 'format': 'email', 'example': 'john@example.com'}
            }
        }
    }
}

if __name__ == '__main__':
    app.run(debug=True)